﻿using CRM.Admin.Contracts.Contract.Customer;
using CRM.Admin.Contracts.Contract.Logs;
using CRM.Admin.Contracts.Dto.Customer;
using CRM.Admin.Contracts.Dto.Logs;
using CRM.Admin.Contracts.Model.Customer;
using CRM.Admin.Services.Service.Logs;
using KingsSharp.Common;
using KingsSharp.Common.Extensions;
using KingsSharp.Common.Filter;
using KingsSharp.Core.Data.Entity;
using KingsSharp.Core.Data.Extensions;
using KingsSharp.Web.Helper;
using KingsSharp.Web.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace CRM.Admin.Areas.Customer.Controllers
{
    /// <summary>
    /// 竞争对手情况
    /// </summary>
    public class CompetitorController : Controller
    {
        public const string CUSTOMER_FILEPATH = "BaseCustomerfiles//";

        /// <summary>
        /// 竞争对手情况业务契约
        /// </summary>
        public ICompetitorService CompetitorService { get; set; }
        

        /// <summary>
        /// 业务日志契约
        /// </summary>
        public IBusinessLogService BusinessLogService { get; set; }

        #region 视图功能
        /// <summary>
        /// 列表页
        /// </summary>
        /// <returns></returns>
        public ActionResult CompetitorIndex()
        {
            return View();
        }

        /// <summary>
        /// 新增页
        /// </summary>
        /// <returns></returns>
        public ActionResult CompetitorAdd(Guid CustomerId)
        {
            ViewBag.CustomerId = CustomerId;
            return View();
        }
        /// <summary>
        /// 编辑页
        /// </summary>
        /// <param name="CompetitorId"></param>
        /// <returns></returns>
        public ActionResult CompetitorEdit(Guid CompetitorId)
        {
            var dto = CompetitorService.Item.Where(a => a.Id == CompetitorId).FirstOrDefault().MapTo<CompetitorDto>();
            return View(dto);
        }

        #endregion

        #region 数据功能
        public ActionResult CompetitorInsert(CompetitorDto dto)
        {
            dto.CheckNotNull(nameof(dto));
            dto.Id = Guid.NewGuid();
            var result = CompetitorService.Insert(dto);
            string Name = dto.Name;
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                BusinessLogService.InsertBusinessLog(new BusinessLogDto()
                {
                    UserName = AppVariable.UserData.UserName,
                    UserId = AppVariable.UserData.UserId,
                    Action = "新增数据",
                    Brower = Request.GetBrowserName(),
                    BusinessId = dto.Id.ToString(),
                    Ip = Request.GetIp(),
                    SystemName = Request.GetSystemName(),
                    Type = typeof(Competitor).ToString(),
                    Content = "竞争对手“{0}”添加到系统当中。".FormatWith(Name)
                });
                msg = "竞争对手“{0}”添加成功。".FormatWith(Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        public ActionResult CompetitorUpdate(CompetitorDto dto)
        {


            dto.CheckNotNull(nameof(dto));
            var result = CompetitorService.Update(dto);
            string msg = result.Message ?? result.ResultType.ToDescription();
            string Name = dto.Name;
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                BusinessLogService.InsertBusinessLog(new BusinessLogDto()
                {
                    UserName = AppVariable.UserData.UserName,
                    UserId = AppVariable.UserData.UserId,
                    Action = "修改数据",
                    Brower = Request.GetBrowserName(),
                    BusinessId = dto.Id.ToString(),
                    Ip = Request.GetIp(),
                    SystemName = Request.GetSystemName(),
                    Type = typeof(Competitor).ToString(),
                    Content = "竞争对手“{0}”于{1}发生了更改。".FormatWith(Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                });
                msg = "竞争对手“{0}”更新成功。".FormatWith(Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        public ActionResult CompetitorDelete(Guid UserId, string CompetitorName)
        {
            var result = CompetitorService.Delete(UserId);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                BusinessLogService.InsertBusinessLog(new BusinessLogDto()
                {
                    UserName = AppVariable.UserData.UserName,
                    UserId = AppVariable.UserData.UserId,
                    Action = "删除数据",
                    Brower = Request.GetBrowserName(),
                    BusinessId = UserId.ToString(),
                    Ip = Request.GetIp(),
                    SystemName = Request.GetSystemName(),
                    Type = typeof(Competitor).ToString(),
                    Content = "竞争对手“{0}”于{1}被删除。".FormatWith(CompetitorName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                });
                msg = "竞争对手“{0}”删除成功。".FormatWith(CompetitorName);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        public ActionResult GetCompetitorGridData()
        {
            GridRequest request = new GridRequest(Request);
            Expression<Func<Competitor, bool>> predicate = FilterHelper.GetExpression<Competitor>(request.FilterGroup);
            int total;
            var data = CompetitorService.Item.OrderBy(o => o.Order)
                .Where(a => a.IsDeleted == false)
                .Where<Competitor, Guid>(predicate, request.PageCondition, out total)
                .Select(s => new
                {
                    s.Id,
                    s.Name,
                    s.ContractDelivery,
                    s.ContractDeliveryPath,
                    s.MarketStrategy,
                    s.MarketStrategyPath,
                    s.Order,
                    s.Problem,
                    s.ProblemPath,
                    s.ProductShare,
                    s.ProQualityLevel,
                    s.ProQualityLevelPath,
                    s.SupplyDesc,
                    s.SupplyDescPath,
                    s.SupplyRelation,
                    s.SupplyRelationPath,
                    s.CreatedTime
                }).ToList();
            return Json(new GridData<object>(data, total), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 图片、附件上传
        /// </summary>
        /// <returns></returns>
        public ActionResult UploaderProcess()
        {
            UploaderResult result = null;
            try
            {
                string path = CUSTOMER_FILEPATH;
                result = new WebUploader().Process(Request, path, file => Guid.NewGuid().ToString() + "_" + file.FileName);
            }
            catch (Exception ex)
            {
                result = new UploaderResult { Message = ex.Message };
                throw new Exception(ex.Message);
            }
            return Json(result);
        }

        #endregion

    }
}